package com.sktlab.bizconfmobile.activity;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.ExecutorService;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.sktlab.bizconfmobile.R;
import com.sktlab.bizconfmobile.model.AccessNumber;
import com.sktlab.bizconfmobile.model.ConferenceAccount;
import com.sktlab.bizconfmobile.model.Constant;
import com.sktlab.bizconfmobile.model.Meeting;
import com.sktlab.bizconfmobile.model.db.AccountsDBAdapter;
import com.sktlab.bizconfmobile.model.db.AccountsDbTable;
import com.sktlab.bizconfmobile.model.db.MeetingDBAdapter;
import com.sktlab.bizconfmobile.model.db.MeetingDbTable;
import com.sktlab.bizconfmobile.model.manager.AccountsManager;
import com.sktlab.bizconfmobile.model.manager.CalendarManager;
import com.sktlab.bizconfmobile.model.manager.ContactManager;
import com.sktlab.bizconfmobile.plistparse.SAXParse;
import com.sktlab.bizconfmobile.util.Util;

/**
 * @Description: welcom screen
 * 
 * @Author wenjuan.li
 * 
 * @date 2013-07-23
 * 
 * @version V1.0
 */
public class WelcomeActivity extends Activity {
	
	public static final String TAG = "WelcomeActivity"; 
	private final int SHOW_MAIN_ACTIVITY = 1;
	private long beginTime = 0;
	private Context mCtx;
	private AssetManager am;
	private AccountsDBAdapter accountDb;
	private MeetingDBAdapter meetingDb;
	
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			switch (msg.what) {

			case SHOW_MAIN_ACTIVITY:

				startMainActivity();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		
		//Util.BIZ_CONF_DEBUG(TAG, "onCreate called~");
		setFullScreen();
		setContentView(R.layout.welcomelogo);
		
		init();
	}
	
	private void init(){
		
		//add some object to this array list, when user clear the phone's memory, the application's memory was cleared
		//too, then we should restart the application to malloc memory.
		//this list is a signal, when application start, add some object to it,if we find its size to 0,we know,our app's
		//memory had been cleared, we should restart our app
		if(AppClass.signal.size() <= 0){
			
			AppClass.signal.add(new ConferenceAccount());
			AppClass.signal.add(new ConferenceAccount());
			AppClass.signal.add(new ConferenceAccount());
		}
		
		mCtx = this;		
		am = getAssets();
		
		beginTime = System.currentTimeMillis();
		
		//This can only be called after ModelManager.initInstance()
		accountDb = new AccountsDBAdapter(AccountsDbTable.ACCOUNTS_DB_TABLE, 
				AccountsDbTable.getAllColumns());
		
		meetingDb = new MeetingDBAdapter(MeetingDbTable.MEETING_DB_TABLE, 
				MeetingDbTable.getAllColumns());
		
		loadData();	
	}

	public void loadData() {

		ExecutorService service = AppClass.getInstance().getService();

		service.submit(new Runnable() {

			@Override
			public void run() {

//				boolean isAccountDownloaded = Util.getSPBoolValue(mCtx,
//						Constant.KEY_SP_ACCOUNT_DOWNLOADED, false);
				
				//if (isAccountDownloaded) {					
					
				//}
				//always load data from database
				loadAccountFromDb();				
				//load meeting from database
				loadMeetingFromDb();
				
				ContactManager.getInstance().Load();

				if (!Util.isEmpty(am)) {
					
					try {
						Locale locale = Locale.getDefault();
						String language = String.format("%s_%s", 
												locale.getLanguage().toLowerCase(), 
												locale.getCountry().toLowerCase());
						
						//Util.BIZ_CONF_DEBUG(TAG, "language: " + language);
						
						InputStream in = null;
						
						if (language.equalsIgnoreCase(Constant.LOCAL_ZH)) {

							in = am.open(Constant.ACCESS_NUMBER_LIST_CH);
						} else {

							in = am.open(Constant.ACCESS_NUMBER_LIST_EN);
						}
						
						SAXParse parser =  new SAXParse();
						List<AccessNumber> list = parser.getAccessNumberList(in);
						
						AppClass.getInstance().setAccessNumberList(list);
					} catch (IOException e) {
						
						e.printStackTrace();
					} catch (Exception e) {
						
						e.printStackTrace();
					}
				}
				
				Long usedTime = System.currentTimeMillis() - beginTime;

				Long sleepTime = Constant.WELCOME_SCREEN_SHOW_TIME - usedTime;

				if (sleepTime <= 0) {

					mHandler.sendEmptyMessage(SHOW_MAIN_ACTIVITY);
				} else {

					mHandler.sendEmptyMessageDelayed(SHOW_MAIN_ACTIVITY, sleepTime);
				}
			}
		});

	}
	
	private void loadMeetingFromDb() {

		ArrayList<Meeting> meetings = CalendarManager.getInstance().getAllMeetings();
		Hashtable<String, ArrayList<Meeting>> dateToMeeting = CalendarManager.getInstance().getDayToConfs();
		
		meetings.clear();
		
		meetingDb.open();
		
		dateToMeeting.clear();
		
		Cursor cursor = meetingDb.fetchAllObjects(null, null);
		
		//just test code
		/************************TEST CODE*****************************/
//		Calendar calendar = Calendar.getInstance();
//		
//		ArrayList<Meeting> test = new ArrayList<Meeting>();
//		
//		Meeting testMeet = new Meeting();		
//		testMeet.setTitle("test");
//		test.add(testMeet);
//		
//		Long testKey = CalendarUtil.transformTimeToKey(calendar.getTimeInMillis());
//		
//		dateToMeeting.put(testKey, test);
		/************************TEST CODE*****************************/
		
		while (cursor.moveToNext()) {
			
			Util.BIZ_CONF_DEBUG(TAG, "meeting has data");
			
			int id = cursor.getInt(cursor
					.getColumnIndex(MeetingDbTable.KEY_ID));
			
			String accountId = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_ACCOUNT_ID));
			
			String title = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_TITLE));
			
			String startDate = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_STARTDATE));
			
			String endDate = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_ENDDATE));
			
			String accessNumber = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_ACCESS_NUMBER));
			
			String notes = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_NOTES));
			
			String invitees = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_INVITEES));
			
			String date = cursor.getString(cursor
					.getColumnIndex(MeetingDbTable.KEY_MEETING_DATE));
			
			Meeting meeting = new Meeting();
			meeting.setAccountId(accountId);
			meeting.setTitle(title);
			meeting.setStartTime(Long.valueOf(startDate));
			meeting.setEndTime(Long.valueOf(endDate));
			meeting.setAccessNumber(accessNumber);
			meeting.setNote(notes);
			meeting.setInvitees(invitees);						
			meeting.setDate(date);
			
			meetings.add(meeting);
		
			if (dateToMeeting.containsKey(date)) {
				
				//Util.BIZ_CONF_DEBUG(TAG, "add meeting,date: " + date);
				dateToMeeting.get(date).add(meeting);
			} else {
				
				ArrayList<Meeting> dateMeetings = new ArrayList<Meeting>();
				dateMeetings.add(meeting);
				dateToMeeting.put(date, dateMeetings);
				//Util.BIZ_CONF_DEBUG(TAG, "new a meeting: date:" + date);
			}
			
		};

		if (cursor != null) {

			cursor.close();
		}

		meetingDb.close();
		
		Util.BIZ_CONF_DEBUG(TAG, "load meeting number: " + dateToMeeting.size());
	}

	private void loadAccountFromDb(){
		
		ArrayList<ConferenceAccount> accounts 
					= AccountsManager.getInstance().getAccounts();
		
		accounts.clear();
		accountDb.open();
		
		Cursor cursor = accountDb.fetchAllObjects(null, null);   			   				
		
		while (cursor.moveToNext()) {

			int id = cursor.getInt(cursor
					.getColumnIndex(AccountsDbTable.KEY_ID));
			String accountName = cursor.getString(cursor
					.getColumnIndex(AccountsDbTable.KEY_ACCOUNT_NAME));
			String confCode = cursor
					.getString(cursor
							.getColumnIndex(AccountsDbTable.KEY_CONFERENCE_CODE));
			String dialInNumber = cursor.getString(cursor
					.getColumnIndex(AccountsDbTable.KEY_DIALINNUMBER));
			String dialOutNumber = cursor
					.getString(cursor
							.getColumnIndex(AccountsDbTable.KEY_DIAL_OUT_NUMBER));
			String moderatorPw = cursor.getString(cursor
					.getColumnIndex(AccountsDbTable.KEY_MODERATOR_PW));
			String securityCode = cursor.getString(cursor
					.getColumnIndex(AccountsDbTable.KEY_SECURITY_CODE));

			int dialOutEnable = cursor
					.getInt(cursor
							.getColumnIndex(AccountsDbTable.KEY_DIAL_OUT_ENABLE));
			int isActive = cursor.getInt(cursor
					.getColumnIndex(AccountsDbTable.KEY_ISACTIVE));
			int securityCodeEnable = cursor
					.getInt(cursor
							.getColumnIndex(AccountsDbTable.KEY_SECURITY_CODE_ENABLE));

			boolean isDialOutEnable = false;
			boolean isSecurityCodeEnable = false;
			boolean activeState = false;
			
			if (dialOutEnable == 1) {

				isDialOutEnable = true;
			}

			if (securityCodeEnable == 1) {

				isSecurityCodeEnable = true;
			}
			
			if (isActive == 1) {
				
				activeState = true;
			}
			
			ConferenceAccount account = new ConferenceAccount(accountName,
						dialInNumber, confCode, dialOutNumber,
						securityCode, isDialOutEnable,
						isSecurityCodeEnable, moderatorPw);
			
			account.setAccountId(id);
			account.setActive(activeState);
			
			Util.BIZ_CONF_DEBUG(TAG, "dial out number" + account.getDialOutNumber());
			
			accounts.add(account);
		};
		
		AccountsManager.getInstance().setAccounts(accounts);
		//AccountManager.getInstance().setAlreadyLoadAccount(true);
		
		if (cursor != null) {
			
			cursor.close();
		}
		
		accountDb.close();
		
		//AccountManager.getInstance().setAlreadyLoadAccount(true);
		
		Util.BIZ_CONF_DEBUG(TAG, "load db account size: " + AccountsManager.getInstance().getAccounts().size());
	}
	
	private void startMainActivity() {

		Intent mainIntent = new Intent(WelcomeActivity.this, MainActivity.class);
		WelcomeActivity.this.startActivity(mainIntent);
		WelcomeActivity.this.finish();
	}

	private void setFullScreen() {
		requestWindowFeature(1);
		getWindow().setFlags(1024, 1024);
	}
}
